/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package siteanaliz;

import java.io.IOException;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.io.*;
import java.util.regex.*;
import java.awt.event.*;
import javax.swing.table.*;
import java.lang.Thread;

/**
 *
 * @author Никита
 */

public class SiteAnaliz {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        MainFrame frame=new MainFrame(1);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}
class MainFrame extends JFrame
{
    public static final int DEFAULT_WIDTH=550;
    public static final int DEFAULT_HEIGHT=600;
    public static boolean lang_f;
    public static boolean YndActive;
    public static boolean GoglActive;
    public static boolean RamActive;
    //элементы для Search панели
    private JButton analizeStart;
    private JTextField SiteAdress;
    
    private JLabel SiteLabel;
    private JLabel KeyLabel;
    private JTextArea OutZone;
     private JMenuBar menuBar;
    private JMenu fileMenu;
    private JMenuItem fileExitMenuItem;
    private JMenuItem Top3;
    // Флаг отображения состояния анализинга.
    private boolean on_progress;
    private JTable table;
    private int SEngine;
    private ButtonGroup group;
    private int DeepDown;
    private String LZ;
    private String SettingEngine;
    JComboBox Deep;
    JComboBox LZC;
    private JRadioButton GoogleB;
    private JRadioButton YandexB;
    private JRadioButton RamblerB;
    private JPopupMenu popup;
    private String SEs;
    private String KEYs;
    private int POSEs;
    // Установить меню “файл”.
   
    public MainFrame(int langzone)
    {
        setTitle("SEO-ANALITICS");
        setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
        SEngine=0;
        DeepDown=50;
        YndActive=false;
        GoglActive=false;
        RamActive=false;
        SettingEngine="";
        LZ="RU";
        if(langzone==1)
        {
            analizeStart=new JButton("Start");
            lang_f=true;
        }
        else   
        {
            analizeStart=new JButton("Начать");
             lang_f=false;
        }
        JPanel SeoPanel = new JPanel();
       
        
        GridBagConstraints constraints;
        GridBagLayout layout = new GridBagLayout();
        SeoPanel.setLayout(layout);
        constraints = new GridBagConstraints();
        
        if(langzone==1)
             SiteLabel = new JLabel("Site domain");
        else 
             SiteLabel = new JLabel("Домен сайта");
       
         constraints.fill = GridBagConstraints.NONE;
         constraints.weightx = 1;
         constraints.gridx = 0;
         constraints.gridwidth = 0;
         constraints.gridy = 0;
         constraints.anchor = GridBagConstraints.WEST;
         constraints.insets = new Insets(20, 20, 0, 0);
       // layout.setConstraints(SiteLabel, constraints);
         SeoPanel.add(SiteLabel, constraints);
        
        
        SiteAdress = new JTextField();
        constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        constraints.insets = new Insets(20,100, 0, 40);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.weightx = 0;
        constraints.gridx = 1;
        constraints.gridy = 0;
        layout.setConstraints(SiteAdress, constraints);
        SeoPanel.add(SiteAdress);
        if(langzone==1)
        {
             SiteAdress.setToolTipText("<sitename>.com/ru/net etc");
        }
        else 
        {
             SiteAdress.setToolTipText("названиесайта.ru/com/net и тп");
        } 
        
        
        constraints = new GridBagConstraints();
        if(langzone==1)
             KeyLabel = new JLabel("Keywords:");
        else 
             KeyLabel = new JLabel("Ключевые слова:");
         constraints.fill = GridBagConstraints.NONE;
         constraints.weightx = 1;
         constraints.gridx = 0;
         constraints.gridwidth = 0;
         constraints.gridy = 4;
         constraints.anchor = GridBagConstraints.WEST;
         constraints.insets = new Insets(20, 20, 0, 0);
       // layout.setConstraints(SiteLabel, constraints);
         SeoPanel.add(KeyLabel, constraints);
         
         
         
        OutZone = new JTextArea(6,30);
        OutZone.setEditable(true);
        JScrollPane scrollPane = new JScrollPane(OutZone,JScrollPane.VERTICAL_SCROLLBAR_NEVER,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);	
        GridBagConstraints constraints1 = new GridBagConstraints();
        constraints1.anchor = GridBagConstraints.WEST;
        constraints1.fill = GridBagConstraints.BOTH;
        constraints1.gridwidth = GridBagConstraints.REMAINDER;
        constraints1.gridheight=4;
        constraints1.weightx = 0;
        constraints1.weighty = 1;
        constraints1.gridx = 2;
        constraints1.gridy = 3;
        constraints1.insets = new Insets(40,100, 20, 40);
        layout.setConstraints(scrollPane, constraints1);
        SeoPanel.add(scrollPane);
        if(langzone==1)
        {
            OutZone.setToolTipText("Tags for search engine");
        }
        else 
        {
            OutZone.setToolTipText("Теги для поиска");
        } 
        
        
        
        //радиобутоны
        JPanel OptionPanel = new JPanel();
        GridBagConstraints propert;
        GridBagLayout layout2 = new GridBagLayout(); 
        GoogleB=new JRadioButton("Google");
        YandexB=new JRadioButton("Yandex");
        RamblerB=new JRadioButton("Rambler");
        Deep=new JComboBox();
        Deep.addItem("50");
        Deep.addItem("100");
        Deep.addItem("200");
        Deep.setEditable(false);
        Deep.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent event)
            {
                DeepDown=Integer.parseInt((String)Deep.getSelectedItem());
            }
        });       
        LZC=new JComboBox();
        LZC.addItem("RU");
        LZC.addItem("EN");
        LZC.setEditable(false);
        LZC.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent event)
            {
                LZ=(String)LZC.getSelectedItem();
            }
        });       
        GoogleB.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
                if(!GoglActive)
                {
                    SEngine++;
                    SettingEngine+="@Google@";
                    GoglActive=true;
                }
                else 
                {
                    SEngine--;
                    SettingEngine=SettingEngine.replaceAll("@Google@", "");
                    GoglActive=false;
                }
                
            }
        });
        YandexB.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
                if(!YndActive)
                {
                    SEngine++;
                    SettingEngine+="@Yandex@";
                    YndActive=true;
                }
                else
                {
                     SEngine--;
                     SettingEngine=SettingEngine.replaceAll("@Yandex@", "");
                     YndActive=false;
                }
            }
        });  
        RamblerB.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
                if(!RamActive)
                {
                    SEngine++;
                    SettingEngine+="@Rambler@";
                    RamActive=true;
                }
                else 
                {
                    SEngine--;
                    SettingEngine=SettingEngine.replaceAll("@Rambler@", "");
                    RamActive=false;
                }
                
            }
        });
         propert = new GridBagConstraints();
         propert.gridx = 0;
         propert.gridy = 1;
         propert.insets = new Insets(5,10, 0, 0);
         layout2.setConstraints(GoogleB, propert);
         
         propert = new GridBagConstraints();
         propert.gridx = 0;
         propert.gridy = 3;
         propert.insets = new Insets(5,10, 0, 0);
         layout2.setConstraints(YandexB, propert);
         
         propert = new GridBagConstraints();
         propert.gridx = 0;
         propert.gridy = 2;
         propert.insets = new Insets(5,10, 0, 0);
         layout2.setConstraints(RamblerB, propert);
         
         propert = new GridBagConstraints();
         propert.gridx = 1;
         propert.gridy = 1;
         propert.insets = new Insets(5,10, 0, 0);
         layout2.setConstraints(Deep, propert);
         
         propert = new GridBagConstraints();
         propert.gridx = 2;
         propert.gridy = 1;
         propert.insets = new Insets(5,10, 0, 0);
         layout2.setConstraints(LZC, propert);
         
         JLabel SearchPro;
          if(langzone==1)
             SearchPro = new JLabel("Search engine:");
        else 
             SearchPro = new JLabel("Поисковик:");
       
         propert = new GridBagConstraints();
         propert.gridx = 0;
         propert.gridy = 0;
         propert.insets = new Insets(5,5, 5, 0);
         layout2.setConstraints(SearchPro, propert);
         
         JLabel DeepS;
          if(langzone==1)
             DeepS = new JLabel("Searching deep:");
        else 
             DeepS = new JLabel("Глубина поиска:");
       
         propert = new GridBagConstraints();
         propert.gridx = 1;
         propert.gridy = 0;
         propert.insets = new Insets(5,30, 5, 0);
         layout2.setConstraints(DeepS, propert);
         
         JLabel LangS;
          if(langzone==1)
             LangS= new JLabel("Language zone:");
        else 
             LangS = new JLabel("Языковая зона:");
       
         propert = new GridBagConstraints();
         propert.gridx = 2;
         propert.gridy = 0;
         propert.insets = new Insets(5,30, 5, 0);
         layout2.setConstraints(LangS, propert);
         
          OptionPanel.setBorder(BorderFactory.createTitledBorder("Options"));
          OptionPanel.setLayout(layout2);
          OptionPanel.add(GoogleB);
         // OptionPanel.add(YandexB);
          OptionPanel.add(RamblerB);
           OptionPanel.add(SearchPro);
           OptionPanel.add(DeepS);
            OptionPanel.add(LangS);
           OptionPanel.add(Deep);
            OptionPanel.add(LZC);
  
         //кнопка 
         if(langzone==1) analizeStart = new JButton("Analize");
         else analizeStart = new JButton("Анализ");
         analizeStart.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
         analizeStarter();
         }
         });
         propert = new GridBagConstraints();
         propert.anchor = GridBagConstraints.SOUTHEAST;
      
         propert.weightx = 1;
         propert.gridx = 3;
         propert.gridy = 10;
         propert.insets = new Insets(10,40, 20, 60);
         layout2.setConstraints(analizeStart, propert);
         OptionPanel.add(analizeStart);
         propert = new GridBagConstraints();
         propert.anchor = GridBagConstraints.SOUTHWEST;
          propert.fill = GridBagConstraints.HORIZONTAL;
         propert.gridx = 0;
         propert.gridy = 10;
         propert.gridwidth = GridBagConstraints.REMAINDER;
         propert.insets = new Insets(10,10, 20, 0);
         layout.setConstraints(OptionPanel, propert);
         SeoPanel.add(OptionPanel);

         
          
          
          
         //таблица  
          final JPanel ResultPanel = new JPanel();
          if(langzone==1)
          {
            table = new JTable(new DefaultTableModel(new Object[][]{},
            new String[]{"Position","Engine","Tag", "URL"})
            {
           public boolean isCellEditable(int row, int column)
           {
                return false;
           }
            });
          
         
          ResultPanel.setBorder(BorderFactory.createTitledBorder("Results"));
          ResultPanel.setLayout(new BorderLayout());
          ResultPanel.add(new JScrollPane(table),BorderLayout.CENTER);
          }
          else 
          {
              table = new JTable(new DefaultTableModel(new Object[][]{},
            new String[]{"Позиция","Поисковик","Тэг", "URL"})
            {
           public boolean isCellEditable(int row, int column)
           {
                return false;
           }
            });
          
          ResultPanel.setBorder(BorderFactory.createTitledBorder("Результаты"));
          ResultPanel.setLayout(new BorderLayout());
          ResultPanel.add(new JScrollPane(table),BorderLayout.CENTER);
          }
          popup=new JPopupMenu();
          Top3 = new JMenuItem("Top3 Concurents");
          
           Top3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new Top3(MainFrame.this,LZ,SEs,KEYs,POSEs).setVisible(true);
            }});
           
          popup.add(Top3);
          
          table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });

     
         //менюха
        
        menuBar = new JMenuBar();
        if(langzone==1)
           fileMenu = new JMenu("File");
        else 
            fileMenu = new JMenu("Файл");
        fileMenu.setMnemonic(KeyEvent.VK_F);
        if(langzone==1)
            fileExitMenuItem = new JMenuItem("Exit",KeyEvent.VK_X);
        else 
            fileExitMenuItem = new JMenuItem("Выход",KeyEvent.VK_X);
        fileExitMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                actionExit();
            }});
         fileMenu.add(fileExitMenuItem);
         menuBar.add(fileMenu);
        setJMenuBar(menuBar);
        
        // Отобразить панели на дисплее.
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(SeoPanel, BorderLayout.NORTH);
        //getContentPane().add(OptionPanel, BorderLayout.EAST);
        getContentPane().add(ResultPanel, BorderLayout.CENTER);
    
        
    }
    private void actionExit() {  System.exit(0);}
     
    private void jTable1MouseClicked(MouseEvent evt) {
        if (evt.getButton() == evt.BUTTON3) {
            
            int column = table.columnAtPoint(new Point(evt.getX(), evt.getY()));
            int row = table.rowAtPoint(new Point(evt.getX(), evt.getY()));
            int selRows  = table.getSelectedRow();
            int selColumns = table.getSelectedColumn();
            
            if ( (selColumns == column) && (selRows == row)) {
                //POSEs=table.getValueAt(selRows,1);
                for(int i=0;i<4;i++)
                {
                    if(table.getColumnName(i).equals("Position") || table.getColumnName(i).equals("Позиция"))
                    {
                        if(table.getValueAt(selRows,i)!="unknown")
                        POSEs=Integer.parseInt(table.getValueAt(selRows,i).toString());
                        else  POSEs=0;
                    }
                    if(table.getColumnName(i).equals("Engine") || table.getColumnName(i).equals("Поисковик")) SEs=table.getValueAt(selRows,i).toString();
                    if(table.getColumnName(i).equals("Tag") || table.getColumnName(i).equals("Тэг")) KEYs=table.getValueAt(selRows,i).toString();
                }
                Top3.setText("Top 3 for this");
                popup.show(table, evt.getX(), evt.getY() );
                
            }
        }
    }
    
    private void analizeStarter() 
    {
        if (on_progress) {
        on_progress = false;
        return;
        }
        ArrayList errorList = new ArrayList();
        Searcher ss=new Searcher(2) ;//для анализа по поисковым движкам
        
        
        String inputURL = SiteAdress.getText().trim();
        if (inputURL.length() < 1) {
            if(lang_f==true)
                errorList.add("Missing site domain.");
            else  errorList.add("Не задан домен сайта");
        }
        
        // Проверить начальный URL.
      
        if(!ss.CorretTag(OutZone.getText())) 
        {
             if(lang_f==true)
                errorList.add("No one keywords");
             else  errorList.add("Отсутствуют ключевые поля");
        }
        if(SEngine==0) 
        {
             if(lang_f==true)
                errorList.add("Choose the searcher!");
             else  errorList.add("Не выбран поисковик");
        }
        // Показать ошибки, если они есть, и возврат.
        if (errorList.size() > 0) 
        {
            StringBuffer message = new StringBuffer();
            // Объединить ошибки в одно сообщение.
            for (int i = 0; i < errorList.size(); i++)
            {
                message.append(errorList.get(i));
                    if (i + 1 < errorList.size()) {
                         message.append("\n");
                     }
            }
            showError(message.toString());
            return;
        }
        try
        { //экшееееееееееееен
           
           // OutZone.append( ss.makeRequest(inputURL));
           
            // Отобразить песочные часы на время работы анализатора.
            
            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            OutZone.setEnabled(false);
            Deep.setEnabled(false);
            LZC.setEnabled(false);
            SiteAdress.setEnabled(false);
            analizeStart.setEnabled(false);
            GoogleB.setEnabled(false);
            RamblerB.setEnabled(false);
           
 
            int timeseg1=0;
            int timeseg2=0;
            System.out.println(SettingEngine);
            System.out.println(LZ);
            
           // Searcher fr=new Searcher("Rambler",LZ);
            
            //ParseEngine w=new ParseEngine();
            //w.ResponseControl(fr.makeRequest(GetKeyWord(1,OutZone.getText())),50);
           // System.out.println(w.RamblerConcurent(2,fr.makeRequest(GetKeyWord(1,OutZone.getText()))));
            
            
            for(int j=0; j<SEngine; j++)
            {
                timeseg1=SettingEngine.indexOf("@",timeseg2)+1;
                timeseg2=SettingEngine.indexOf("@",timeseg1)+1;
                System.out.println(SettingEngine.substring(timeseg1, timeseg2-1));
                //System.out.println("ключ "+GetKeyWord(1,OutZone.getText()));
                String gg=SettingEngine.substring(timeseg1, timeseg2-1);
                
                 for(int i=1;i<=5;i++)
                {
                    String rt=GetKeyWord(i,OutZone.getText());
                    if(!rt.equals("<<#$%enought%$#>>"))
                    {
                        if(ss.CorretTag(rt))
                        {
                              //System.out.println("кей "+ rt+" s="+SEngine+" i="+i);
                            
                            rt=rt.trim();
                            rt=ss.GetStyleRequestString(rt);
                            JobRunnable rn=new JobRunnable(LZ,DeepDown,SettingEngine.substring(timeseg1, timeseg2-1),inputURL,rt,table, OutZone,Deep,LZC,SiteAdress,analizeStart,RamblerB,GoogleB);
                            Thread th=new Thread(rn);
                            th.setName(Integer.toString(i));
                            th.start();
                        }
                    }
                }
            }
     
       
            //OutZone.append(pp.YandexConcurent(2, ss.makeRequest(inputURL)));
           // Thread.sleep(4000);
        }
        catch (Exception e) 
        {
              errorList.add("Shit happened");    
              
        }
        finally
        {
             // Возвратить курсор по умолчанию.
            setCursor(Cursor.getDefaultCursor());
//            OutZone.setEnabled(true);
//            Deep.setEnabled(true);
//            LZC.setEnabled(true);
//            SiteAdress.setEnabled(true);
//            analizeStart.setEnabled(true);
//            GoogleB.setEnabled(true);
//            YandexB.setEnabled(true);
        }
         if (errorList.size() > 0) 
        {
            StringBuffer message = new StringBuffer();
            // Объединить ошибки в одно сообщение.
            for (int i = 0; i < errorList.size(); i++)
            {
                message.append(errorList.get(i));
                    if (i + 1 < errorList.size()) {
                         message.append("\n");
                     }
            }
            showError(message.toString());
            return;
        }
          
         
 
     }
    
    // Отобразить диалоговое окно с сообщением об ошибке.
    private void showError(String message)
    {
        if(lang_f==true)
            JOptionPane.showMessageDialog(this, message, "Error",JOptionPane.ERROR_MESSAGE);
        else JOptionPane.showMessageDialog(this, message, "Ошибка",JOptionPane.ERROR_MESSAGE);
    }   
     
    private void addPosition(String url, String position,String engine, String tag, JTable table1 ) {
 // Добавить URL в таблицу совпадений.
    DefaultTableModel model =
    (DefaultTableModel) table1.getModel();
    model.addRow(new Object[]{position,engine,tag,url});
  
    }
    
     public String GetKeyWord(int count, String TxtArea)
    {
        int firstiter=0;
        int seconditer=0;
        int middleiter=0;
        int cashiter=0;
        boolean checkeof=false;
        for(int i=0; i<count; i++)
        {
            if(i>0)
            {
                if(TxtArea.indexOf(",",middleiter)==-1)
                {
                    
                    firstiter=TxtArea.indexOf("\n",middleiter);//TxtArea.indexOf(",",middleiter)
                    if(firstiter==-1)
                    {
                        firstiter=TxtArea.length();
                        seconditer=middleiter;
                        if(i+1<count) return "<<#$%enought%$#>>";
                        return  TxtArea.substring(seconditer, firstiter);
                    }
                    seconditer=middleiter;
                    middleiter=firstiter+1;
                    checkeof=true;
                }
                else
                {
                   
                    firstiter=TxtArea.indexOf(",",middleiter);
                    cashiter=TxtArea.indexOf("\n",middleiter);
                    if(cashiter<firstiter && cashiter!=-1) firstiter=cashiter;
                    if(firstiter==-1)
                    {
                        firstiter=TxtArea.length();
                        seconditer=middleiter;
                        if(i+1<count) return "<<#$%enought%$#>>";
                        return  TxtArea.substring(seconditer, firstiter);
                    }
                     seconditer=middleiter;
                     middleiter=firstiter+1;
                     checkeof=true;
                }
            }
            else
            {
                if(TxtArea.indexOf(",")==-1)
                {
                    firstiter=TxtArea.indexOf("\n");
                    if(firstiter==-1)
                    {
                        firstiter=TxtArea.length();
                         if(i+1<count) return "<<#$%enought%$#>>";
                        return  TxtArea.substring(0, firstiter);
                    }
                    middleiter=firstiter+1;
                    checkeof=true;
                }
                else
                {
                    
                    firstiter=TxtArea.indexOf(",");
                    cashiter=TxtArea.indexOf("\n",middleiter);
                    if(cashiter<firstiter && cashiter!=-1) firstiter=cashiter;
                    if(firstiter==-1)
                    {
                        firstiter=TxtArea.length();
                         if(i+1<count) return "<<#$%enought%$#>>";
                        return  TxtArea.substring(0, firstiter);
                    }
                    middleiter=firstiter+1;
                    checkeof=true;
                }
            }
        }
        if(checkeof==false) return TxtArea;
        return  TxtArea.substring(seconditer, firstiter);
       
    }
 
    
    // Установить меню “файл”.
   
}

